<template>
  <div>
    <div>深度冲突(模型闪烁)</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';

  // import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
  // import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  onMounted(() => {
    init();
  });

  function init() {
    const scene = new THREE.Scene();
    const width = 800;
    const height = 500;
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(500, 500, 500);
    camera.lookAt(scene.position);
    const render = new THREE.WebGLRenderer({
      //想把canvas画布上内容下载到本地，需要设置为true
      // preserveDrawingBuffer: true,
      // 设置对数深度缓冲区，优化深度冲突问题
      logarithmicDepthBuffer: true,
    });
    render.setSize(width, height);
    // console.log(' webgl.value', webgl.value);

    webgl.value.appendChild(render.domElement);
    // document.body.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    // 两个矩形平面Mesh重合，产生闪烁
    // 闪烁原因：两个矩形面位置重合，GPU无法分清谁在前谁在后
    const geometry = new THREE.PlaneGeometry(250, 250);
    const material = new THREE.MeshLambertMaterial({
      color: 0x00ffff,
      side: THREE.DoubleSide,
    });
    const mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    const geometry2 = new THREE.PlaneGeometry(300, 300);
    const material2 = new THREE.MeshLambertMaterial({
      color: 0xff6666,
      side: THREE.DoubleSide,
    });
    const mesh2 = new THREE.Mesh(geometry2, material2);
    mesh2.position.z = 0.3;
    scene.add(mesh2);

    render.setClearColor(0xb9d3ff, 1);

    function renderFun() {
      // console.log('asdfasdf');
      render.render(scene, camera);
      requestAnimationFrame(renderFun);
    }
    renderFun();
  }
</script>
